<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <title>精美贪吃蛇游戏</title>
  <style>
    body {
      display: flex;
      flex-direction: column;
      align-items: center;
      background: linear-gradient(135deg, #1a1a1a, #4a4a4a);
      color: white;
      font-family: 'Arial', sans-serif;
      min-height: 100vh;
      margin: 0;
      padding: 20px;
    }

    #game-container {
      position: relative;
      margin: 20px;
    }

    #game-canvas {
      border: 3px solid #2ecc71;
      border-radius: 10px;
      box-shadow: 0 0 20px rgba(46, 204, 113, 0.3);
    }

    .controls {
      display: flex;
      gap: 15px;
      margin: 20px 0;
    }

    button {
      padding: 12px 24px;
      font-size: 16px;
      border: none;
      border-radius: 25px;
      background: #2ecc71;
      color: white;
      cursor: pointer;
      transition: all 0.3s ease;
      text-transform: uppercase;
      letter-spacing: 1px;
    }

    button:hover {
      background: #27ae60;
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4);
    }

    .score-board {
      font-size: 24px;
      margin: 15px 0;
      text-align: center;
    }

    #difficulty {
      padding: 10px;
      border-radius: 25px;
      background: #34495e;
      color: white;
      border: 2px solid #2ecc71;
    }
  </style>
</head>

<body>
  <div class="score-board">
    当前得分: <span id="score">0</span> |
    最高分: <span id="high-score">0</span>
  </div>

  <div id="game-container">
    <canvas id="game-canvas" width="600" height="400"></canvas>
  </div>

  <div class="controls">
    <button id="start-btn">开始游戏</button>
    <button id="pause-btn">暂停/继续</button>
    <select id="difficulty">
      <option value="150">简单</option>
      <option value="100">中等</option>
      <option value="70">困难</option>
    </select>
  </div>

  <script>
    const canvas = document.getElementById('game-canvas');
    const ctx = canvas.getContext('2d');
    const GRID_SIZE = 20;
    const GRID_COUNT = canvas.width / GRID_SIZE;

    let snake = [];
    let food = {};
    let direction = 'right';
    let nextDirection = 'right';
    let gameLoop;
    let isPaused = false;
    let score = 0;
    let highScore = localStorage.getItem('snakeHighScore') || 0;

    // 初始化游戏
    function initGame() {
      snake = [
        { x: 5, y: 5 },
        { x: 4, y: 5 },
        { x: 3, y: 5 }
      ];
      generateFood();
      direction = 'right';
      nextDirection = 'right';
      score = 0;
      updateScore();
    }

    // 生成食物
    function generateFood() {
      while (true) {
        food = {
          x: Math.floor(Math.random() * (canvas.width / GRID_SIZE)),
          y: Math.floor(Math.random() * (canvas.height / GRID_SIZE))
        };
        if (!snake.some(segment => segment.x === food.x && segment.y === food.y)) break;
      }
    }

    // 游戏循环
    function gameUpdate() {
      if (isPaused) return;

      direction = nextDirection;
      const head = { ...snake[0] };

      switch (direction) {
        case 'up': head.y--; break;
        case 'down': head.y++; break;
        case 'left': head.x--; break;
        case 'right': head.x++; break;
      }

      // 碰撞检测
      if (head.x < 0 || head.x >= canvas.width / GRID_SIZE ||
        head.y < 0 || head.y >= canvas.height / GRID_SIZE ||
        snake.some(segment => segment.x === head.x && segment.y === head.y)) {
        gameOver();
        return;
      }

      snake.unshift(head);

      // 吃食物检测
      if (head.x === food.x && head.y === food.y) {
        score += 10;
        updateScore();
        generateFood();
      } else {
        snake.pop();
      }

      draw();
    }

    // 绘制游戏
    function draw() {
      // 清除画布
      ctx.fillStyle = '#2c3e50';
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      // 绘制蛇
      snake.forEach((segment, index) => {
        ctx.fillStyle = index === 0 ? '#e74c3c' :
          `hsl(${150 + index * 5}, 70%, 50%)`;
        ctx.beginPath();
        ctx.roundRect(
          segment.x * GRID_SIZE,
          segment.y * GRID_SIZE,
          GRID_SIZE - 1,
          GRID_SIZE - 1,
          5
        );
        ctx.fill();
      });

      // 绘制食物
      ctx.fillStyle = '#2ecc71';
      ctx.beginPath();
      ctx.arc(
        food.x * GRID_SIZE + GRID_SIZE / 2,
        food.y * GRID_SIZE + GRID_SIZE / 2,
        GRID_SIZE / 2 - 2,
        0,
        Math.PI * 2
      );
      ctx.fill();
    }

    function updateScore() {
      document.getElementById('score').textContent = score;
      if (score > highScore) {
        highScore = score;
        localStorage.setItem('snakeHighScore', highScore);
        document.getElementById('high-score').textContent = highScore;
      }
    }

    function gameOver() {
      clearInterval(gameLoop);
      alert(`游戏结束！得分：${score}`);
    }

    // 事件监听
    document.addEventListener('keydown', (e) => {
      switch (e.key) {
        case 'ArrowUp':
          if (direction !== 'down') nextDirection = 'up';
          break;
        case 'ArrowDown':
          if (direction !== 'up') nextDirection = 'down';
          break;
        case 'ArrowLeft':
          if (direction !== 'right') nextDirection = 'left';
          break;
        case 'ArrowRight':
          if (direction !== 'left') nextDirection = 'right';
          break;
      }
    });

    // 控制按钮
    document.getElementById('start-btn').addEventListener('click', () => {
      clearInterval(gameLoop);
      initGame();
      gameLoop = setInterval(gameUpdate, document.getElementById('difficulty').value);
    });

    document.getElementById('pause-btn').addEventListener('click', () => {
      isPaused = !isPaused;
    });

    document.getElementById('difficulty').addEventListener('change', () => {
      clearInterval(gameLoop);
      gameLoop = setInterval(gameUpdate, document.getElementById('difficulty').value);
    });

    // 初始化最高分
    document.getElementById('high-score').textContent = highScore;
  </script>
</body>

</html>